<script setup  lang="ts">
import type { CurrencyBalance, CurrencyTokenDetail } from '~/api/services/main.api';
import { CurrencyList } from '~/components/currency';
import { jsBridge } from '~/utils/defines';

export interface SelectTokenProps {
  list: Array<CurrencyBalance & { disabled: boolean }>;
  labels?: [string, string];
  onSelectCurrency?: (data: { currency: string; chain: string; isFiat: boolean; currencyInfo: CurrencyBalance; isFirst: boolean }) => void;
  showBalance?: boolean;
  disabledKey: keyof CurrencyTokenDetail;
};

const props = defineProps<SelectTokenProps>();

const slots = defineSlots<{ chain?: () => any }>();

const { cryptoName } = storeToRefs(useCurrencyStore());

const currencyNameRef = defineModel<string>('currency');
const chainRef = defineModel<string>('chain');
const isFiatRef = defineModel<boolean>('isFiat', { default: false });

const getCurrencyOptionsRef = computed(() => (props.list || []).map(x => ({
  ...x,
  value: x.currency,
  label: x.currency,
})));

const getChainOptionsRef = computed(() => {
  const list = (props.list || []).find(x => x.currency === currencyNameRef.value);
  return list?.tokens?.map(x => ({
    value: x.chain,
    label: `${x.chain} (${x.network})`,
    disabled: x?.[props.disabledKey] === 0,
  })) || [];
});

const $currencySelect = ref();

function blurCurrencySelect() {
  $currencySelect.value?.blur?.();
  const parentEle: HTMLElement = $currencySelect.value?.$el.parentElement;
  const clickEv = new MouseEvent('mousedown', { bubbles: true, cancelable: true });
  parentEle?.dispatchEvent(clickEv);
}

function selectCurrency(name: string, isFirst: boolean) {
  if (name === currencyNameRef.value)
    return;

  const currencyInfo = getCurrencyOptionsRef.value.find(item => item.currency === name);
  const chainInfo = currencyInfo?.tokens?.[0];

  if (!currencyInfo)
    return;

  currencyNameRef.value = currencyInfo.currency;
  chainRef.value = chainInfo?.chain ?? '';
  isFiatRef.value = !!currencyInfo.is_fiat;

  jsBridge.post('rechargeClick', { isFiat: currencyInfo.is_fiat, currency: name });
  props.onSelectCurrency?.({
    currency: currencyInfo.currency,
    chain: chainInfo?.chain ?? '',
    isFiat: !!currencyInfo.is_fiat,
    currencyInfo,
    isFirst,
  });
}

watch(getCurrencyOptionsRef, (val) => {
  if (val?.length && !currencyNameRef.value) {
    const _defC = val.find(x => !x.disabled);
    // if (envs.isTg) {
    //   const ton = val.find(x => !x.disabled && x.currency?.toLowerCase?.() === ('ton').toLowerCase()) || _defC;
    //   ton && selectCurrency(ton.currency, true);
    //   return;
    // }
    if (cryptoName.value) {
      const _def = val.find(x => !x.disabled && x.currency?.toLowerCase?.() === cryptoName.value?.toLowerCase?.()) || _defC;
      _def && selectCurrency(_def.currency, true);
      return;
    }
    _defC && selectCurrency(_defC.currency, true);
  }
}, { immediate: true });

const currencyListDomRef = ref();

async function dropdownVisibleChange(open: boolean) {
  if (open && !envs.isMobile) {
    await nextTick();
    setTimeout(() => {
      currencyListDomRef.value?.focusSearch?.();
    }, 200);
  }
}
</script>

<template>
  <div class="grid grid-cols-2 w-full gap-x-3 gap-y-1.5">
    <div v-if="labels?.length === 2" class="text-sm text-sys-text-body">
      {{ labels?.[0] }}
    </div>
    <div v-if="labels?.length === 2" class="text-sm text-sys-text-body">
      {{ labels?.[1] }}
    </div>

    <ASelect
      ref="$currencySelect"
      :value="currencyNameRef"
      :options="getCurrencyOptionsRef"
      :dropdownMatchSelectWidth="false"
      :listHeight="300"
      :placeholder="$t('wLgpseupa9rR91c7PgiAk')"
      @dropdownVisibleChange="dropdownVisibleChange"
    >
      <template #optionLabel="option">
        <div v-if="option" class="flex items-center gap-2">
          <TCurrencyIcon :symbol="option.value" size="1.125rem" />
          <div>{{ option.label }}</div>
        </div>
      </template>
      <template v-if="getCurrencyOptionsRef.length" #dropdownRender>
        <CurrencyList
          ref="currencyListDomRef"
          :value="currency"
          class="pointer-events-auto w-60 p-1.5"
          listClass="max-h-45"
          :currencyList="getCurrencyOptionsRef"
          :showConvertToFiatBtn="false"
          :showBalance="props.showBalance"
          :showHideZeroBalanceBtn="props.showBalance"
          @update:value="selectCurrency($event ?? '', false)"
          @close="blurCurrencySelect()"
        />
      </template>
    </ASelect>

    <slot v-if="slots.chain" name="chain" />

    <ASelect
      v-else
      v-model:value="chainRef"
      :options="getChainOptionsRef"
      :dropdownMatchSelectWidth="false"
      :listHeight="300"
      :placeholder="$t('ouZrIcqBlEOk47IdYiz38')"
    />
  </div>
</template>
